package com.qys.livesMall.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.qys.livesMall.common.enums.CommonPassFlag;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.constants.ShopSellTaskStatus;
import com.qys.livesMall.shop.dao.H2ShopBaseDao;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuMapper;
import com.qys.livesMall.shop.mapper.ShopGoodsSkuStocksMapper;
import com.qys.livesMall.shop.modal.dto.task.app.SellTaskShopPageDTO;
import com.qys.livesMall.shop.modal.dto.task.app.ShopSellTaskSaveDTO;
import com.qys.livesMall.shop.modal.dto.task.app.child.SellTaskSaveChild;
import com.qys.livesMall.shop.modal.dto.task.sys.SysShopSellTaskPageDTO;
import com.qys.livesMall.shop.modal.entity.*;
import com.qys.livesMall.shop.mapper.ShopSellTaskMapper;
import com.qys.livesMall.shop.modal.vo.SellLivesChild;
import com.qys.livesMall.shop.modal.vo.task.app.SellTaskDetailVo;
import com.qys.livesMall.shop.modal.vo.task.app.SellTaskShopPageVo;
import com.qys.livesMall.shop.modal.vo.task.app.child.SellTaskGoodsChild;
import com.qys.livesMall.shop.modal.vo.task.sys.SysShopSellTaskPageVo;
import com.qys.livesMall.shop.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 店铺带货任务表 服务实现类
 * </p>
 *
 * @author
 * @since 2023-06-15
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShopSellTaskServiceImpl extends ServiceImpl<ShopSellTaskMapper, ShopSellTask> implements ShopSellTaskService {

    private final ShopSellTaskProductService shopSellTaskProductService;
    private final H2ShopBaseService h2ShopBaseService;
    private final H2ShopBaseDao h2ShopBaseDao;
    private final ShopGoodsInfoService goodsInfoService;
    private final H2ShopLevelService levelService;
    private final ShopGoodsSkuMapper goodsSkuMapper;
    private final ShopGoodsSkuStocksMapper skuStocksMapper;
    private final ShopSellTaskProductService taskProductService;

    /**
     * 发布带货任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void releaseTask(ShopSellTaskSaveDTO saveDTO) {
        log.info("APP店铺发布带货任务,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), saveDTO);
        //判断时间
        if (saveDTO.getTaskStartTime().isBefore(LocalDate.now())) {
            throw new QysException(MessageUtils.message("开始结束需在当前时间之后"));
        }
        //判断时间
        if (saveDTO.getTaskStartTime().isAfter(saveDTO.getTaskEndTime())) {
            throw new QysException(MessageUtils.message("结束时间须在开始时间之后"));
        }

        H2ShopBase shopBase = h2ShopBaseService.queryShopBaseByUserId(SecurityUtils.getUserId());
        /**是否允许发起任务*/
        if (!levelService.allowOperation(shopBase.getShopLevelId(), 4)) {
            throw new QysException("店铺所在等级已禁止该操作");
        }
        ShopSellTask task = new ShopSellTask();
        BeanUtil.copyProperties(saveDTO, task);
        task.setCreateTime(LocalDateTime.now());
        task.setShopBaseId(shopBase.getId());
        task.setShopName(shopBase.getShopName());
        task.setStatus(ShopSellTaskStatus.审核中.getStatus());
        task.setPassFlag(CommonPassFlag.审核中.getStatus());
        task.setDeleted((byte) 0);
        task.setNeedReputation(0);
        List<SellTaskSaveChild> shopGoodsInfoList = saveDTO.getShopGoodsInfoList();
        List<String> goodsInfoNameList = shopGoodsInfoList.stream().map(SellTaskSaveChild::getShopGoodsInfoName).toList();
        task.setTaskProductName(String.join(";", goodsInfoNameList));
        baseMapper.insert(task);

        //关联信息
        shopSellTaskProductService.updateAndSave(task.getId(), shopGoodsInfoList);
    }

    /**
     * 修改任务
     *
     * @param saveDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTask(ShopSellTaskSaveDTO saveDTO) {
        log.info("APP店铺修改带货任务,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), saveDTO);
        ShopSellTask task = checkAudit(saveDTO.getId());
        Long shopBaseId = h2ShopBaseDao.queryShopBaseIdByUserId(SecurityUtils.getUserId());
        if (!task.getShopBaseId().equals(shopBaseId)) {
            throw new QysException(MessageUtils.message("不是自己店铺发布任务"));
        }
        //判断时间
        if (saveDTO.getTaskStartTime().isBefore(LocalDate.now())) {
            throw new QysException(MessageUtils.message("开始结束需在当前时间之后"));
        }
        if (saveDTO.getTaskStartTime().isAfter(saveDTO.getTaskEndTime())) {
            throw new QysException(MessageUtils.message("结束时间须在开始时间之后"));
        }
        BeanUtil.copyProperties(saveDTO, task);
        task.setUpdateTime(LocalDateTime.now());
        List<SellTaskSaveChild> shopGoodsInfoList = saveDTO.getShopGoodsInfoList();
        List<String> goodsInfoNameList = shopGoodsInfoList.stream().map(SellTaskSaveChild::getShopGoodsInfoName).toList();
        task.setTaskProductName(String.join(";", goodsInfoNameList));
        baseMapper.updateById(task);

        //关联信息
        shopSellTaskProductService.updateAndSave(task.getId(), shopGoodsInfoList);
    }

    /**
     * 任务详情
     *
     * @param id
     */
    @Override
    public SellTaskDetailVo taskDetail(Long id) {
        ShopSellTask task = baseMapper.selectById(id);
        if (null == task) {
            throw new QysException("请检查ID");
        }
        SellTaskDetailVo vo = new SellTaskDetailVo();
        BeanUtil.copyProperties(task, vo);
//        Long shopBaseId = h2ShopBaseDao.queryShopBaseIdByUserId(SecurityUtils.getUserId());
//        if (null != shopBaseId && null != task.getShopBaseId()) {
//            vo.setMyFlag(shopBaseId.equals(task.getShopBaseId()));
//        }

        List<Long> goodsInfoIdList = shopSellTaskProductService.listGoodsInfoIdBySellTaskId(id);
        if (goodsInfoIdList.size() > 0) {
            List<ShopGoodsInfo> list = goodsInfoService.list(Wrappers.<ShopGoodsInfo>lambdaQuery().in(ShopGoodsInfo::getId, goodsInfoIdList));
            List<SellTaskGoodsChild> goodsChildList = Lists.newArrayList();
            for (ShopGoodsInfo goodsInfo : list) {
                SellTaskGoodsChild sellTaskGoodsChild = new SellTaskGoodsChild();
                BeanUtil.copyProperties(goodsInfo, sellTaskGoodsChild);
                //总库存
                List<ShopGoodsSku> shopGoodsSkus = goodsSkuMapper.selectList(Wrappers.<ShopGoodsSku>lambdaQuery().eq(ShopGoodsSku::getShopGoodsId, goodsInfo.getId()));
                List<Long> skuId = shopGoodsSkus.stream().map(ShopGoodsSku::getId).toList();
                ShopGoodsSkuStocks skuStocks = skuStocksMapper.selectOne(Wrappers.<ShopGoodsSkuStocks>query().select("sum(num) as num").in("sku_id", skuId).eq("state", 0));
                sellTaskGoodsChild.setInventory(Optional.ofNullable(skuStocks.getNum()).orElse(0));
                //带货数量
                ShopSellTaskProduct one = shopSellTaskProductService.getOne(Wrappers.<ShopSellTaskProduct>lambdaQuery()
                        .eq(ShopSellTaskProduct::getShopSellTaskId, id)
                        .eq(ShopSellTaskProduct::getShopGoodsInfoId, goodsInfo.getId())
                );
                if(one != null){
                    sellTaskGoodsChild.setQuantitySold(one.getQuantitySold());
                }
                goodsChildList.add(sellTaskGoodsChild);
            }
            vo.setGoodsChildList(goodsChildList);
        } else {
            vo.setGoodsChildList(new ArrayList<>());
        }
        return vo;
    }

    @Override
    public Page<SellTaskShopPageVo> pageByApp(SellTaskShopPageDTO queryDTO) {
        Page<SellTaskShopPageVo> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        return baseMapper.listByAppPage(page, queryDTO);
    }

    @Override
    public Page<SysShopSellTaskPageVo> pageBySys(SysShopSellTaskPageDTO queryDTO) {
        Page<SysShopSellTaskPageVo> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        Page<SysShopSellTaskPageVo> pageList = baseMapper.listByAppSys(page, queryDTO);
        pageList.getRecords().forEach(e->{
            List<ShopSellTaskProduct> products = taskProductService.list(Wrappers.<ShopSellTaskProduct>lambdaQuery().eq(ShopSellTaskProduct::getShopSellTaskId, e.getId()));
            List<Long> goodsId = products.stream().map(ShopSellTaskProduct::getShopGoodsInfoId).toList();
            List<SellLivesChild> sellLivesChildren = BeanUtil.copyToList(goodsInfoService.list(Wrappers.<ShopGoodsInfo>lambdaQuery().in(!CollectionUtils.isEmpty(goodsId), ShopGoodsInfo::getId, goodsId).orderByDesc(ShopGoodsInfo::getCreateTime)), SellLivesChild.class);
            sellLivesChildren.forEach(child->{
                List<ShopSellTaskProduct> taskProducts = products.stream().filter(p -> Objects.equals(p.getShopGoodsInfoId(), child.getId())).toList();
                //带货数量
                child.setQuantitySold(taskProducts.get(0).getQuantitySold());
            });
            e.setGoodsChildList(sellLivesChildren);
        });
        return pageList;
    }


    @Override
    public void noPass(Long id) {
        log.info("后台管理未通过审核带货任务,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), id);
        ShopSellTask task = checkAudit(id);
        task.setStatus(ShopSellTaskStatus.未通过审核.getStatus());
        task.setPassFlag(CommonPassFlag.审核未通过.getStatus());
        updateById(task);
    }

    @Override
    public Integer pass(Long id) {
        log.info("后台管理通过审核带货任务,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), id);
        ShopSellTask task = checkAudit(id);
        //判断审核时间
        if (task.getTaskEndTime().isBefore(LocalDate.now())) {
            task.setStatus(ShopSellTaskStatus.未通过审核.getStatus());
            task.setPassFlag(CommonPassFlag.审核未通过.getStatus());
            updateById(task);
            return 1;
        }
        task.setStatus(ShopSellTaskStatus.进行中.getStatus());
        task.setPassFlag(CommonPassFlag.审核通过.getStatus());
        updateById(task);
        return 0;
    }

    /**
     * 判断带货是否允许
     */
    @Override
    public ShopSellTask checkSellTask(Long sellTaskId) {
        ShopSellTask sellTask = baseMapper.selectById(sellTaskId);
        if (null == sellTask) {
            throw new QysException(MessageUtils.message("带货任务不存在"));
        }
        if (2 != sellTask.getPassFlag() || 2 != sellTask.getStatus()) {
            throw new QysException(MessageUtils.message("带货任务不存在"));
        }
        return sellTask;
    }

    @Override
    public List<ShopSellTask> getByGoodsId(Long goodsId, Long shopId) {
        return baseMapper.getByGoodsId(goodsId,shopId);
    }

    private ShopSellTask checkAudit(Long id) {
        ShopSellTask task = baseMapper.selectById(id);
        if (null == task) {
            throw new QysException("请检查ID");
        }
        ShopSellTaskStatus.checkStatus(task.getStatus(), ShopSellTaskStatus.审核中);
        return task;
    }
}
